extends Node2D
class_name CardView

@onready var mask = $Mask
@onready var card_state_machine: CardStateMachine = $CardStateMachine as CardStateMachine
@onready var border_panel = $BorderPanel

@export var HAND_STYLEBOX: StyleBoxFlat
@export var PICKUP_STYLEBOX: StyleBoxFlat
@export var HOVER_STYLEBOX: StyleBoxFlat
@export var USE_STYLEBOX: StyleBoxFlat
var CARD_INTRODUCE_DIR = Globals.CARD_INTRODUCE_DIR
var card_container = null
var card: Card:
	set(value):
		card = value
		var desc_label: RichTextLabel = %DescRichTextLabel
		var name_label = %NameLabel
		var point_label = %PointLabel
		var card_icon: TextureRect = %CardIcon
		var type_label = %TypeLabel

		var introduce = CARD_INTRODUCE_DIR[value.name_lab]
		card.init_from_csv(introduce)
		card.update_attribute()
		name_label.set_text(introduce[3])
		point_label.set_text(str(card.point))
		desc_label.set_text(card.get_desc())
		type_label.set_text(introduce[1])
		card_icon.texture = value.icon

var tween: Tween
@export var trophy_mode: bool = false

signal play_on_release_signal
signal play_on_release_signal_finish

var can_use = true

func _ready():
	card_state_machine.init(self)
	card_state_machine.trophy_mode = trophy_mode
	play_on_release_signal.connect(_on_play_on_release_signal)


func _process(_delta):
	if Input.is_action_just_pressed("select_card"):
		if can_use:
			card_state_machine.on_card_select()
		return
	if Input.is_action_just_released("select_card"):
		if can_use:
			card_state_machine.on_card_release()
		return


func update_transform(in_hand_rotation, in_hand_position, in_hand_hover_position):
	card_state_machine.update_transform(in_hand_rotation, in_hand_position, in_hand_hover_position)


func _on_mask_mouse_entered():
	if can_use:
		card_state_machine.on_mouse_entered()


func _on_mask_mouse_exited():
	if can_use:
		card_state_machine.on_mouse_exited()


func should_show_arrow() -> bool:
	if CardManager.round_data.card_switch_select_mode:
		return false
	return card.card_type == Card.CARD_TYPE.COM


func _on_play_on_release_signal():
	if can_use:
		card.play_on_release(self)


func play_on_release() -> void:
	if can_use:
		card.play_on_release(self)


func play_on_release_after():
	if can_use:
		card.play_on_release_after(self)


func update_label():
	var desc_label: RichTextLabel = %DescRichTextLabel
	var point_label = %PointLabel
	point_label.set_text(str(card.point))
	desc_label.set_text(card.get_desc())


func update_label_on_pickup(card_can_use, target):
	var desc_label: RichTextLabel = %DescRichTextLabel
	if card_can_use:
		desc_label.set_text(card.get_desc_on_target(target))
	else:
		desc_label.set_text(card.get_desc())
